package com.personnalManagerSystem.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;

@Slf4j
public class FileUtil {
    //上传文件
    public static JSONResult upload(MultipartFile file) {
        //获取上传时时间
        long startTime = System.currentTimeMillis();
        //文件保存路径
        String filePath = "";
        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        log.info("fileName---------" + originalFilename);
        //截取文件名"."前面的字符长度
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //截取文件名"."后面部分，文件类型
        String fileType = originalFilename.substring(lastIndexOf + 1);
        log.info("截取文件名类型:{}", fileType);
        //文件类型判断 jpg,png,gif
        if (fileType.equals("jpg") || fileType.equals("png") ||
                fileType.equals("dox") || fileType.equals("docx") || fileType.equals("xls")) {
            //文件保存路径
            filePath = "D:/upload/" + new Date().getTime() + originalFilename;
            try {
                log.info(URLEncoder.encode(ResourceUtils.getURL("classpath:static").getPath(), "GBK"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            //创建File对象
            File newFile = new File(filePath);
            if (newFile.exists()) {
                log.info("文件路径已存在");
            } else {
                log.info("文件路径不存在，正在创建");
                newFile.mkdirs();
            }
            try {
                //通过CommonsMultipartFile的方法直接写文件(注意这个时候）
                file.transferTo(newFile);
                //文件传输时间
                long endTime = System.currentTimeMillis();
                log.info("采用file.Transto的运行时间：" + String.valueOf(endTime
                        - startTime) + "ms");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return JSONResult.errorMsg("不允许该\" + fileType + \"文件类型上传");
        }
        return JSONResult.ok();
    }

    //下载文件
    public static JSONResult download(String url, HttpServletResponse response) throws Exception {
        log.info("--------1-------" + url);
        String strUrl = url;
        //截取字符串
        int i = 10;
        String urlstr = url.substring(i);
        System.out.println("--------2-------" + urlstr);
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(strUrl)));
        //假如以中文名下载的话
        String filename = urlstr;
        //转码，免得文件名中文乱码
        filename = URLEncoder.encode(filename, "UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename="
                + filename);
        //设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while ((len = bis.read()) != -1) {
            out.write(len);
            out.flush();
        }
        out.close();
        return JSONResult.ok();
    }
}
